package com.dudu.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.dudu.enumeration.H5CodeDefinition;
import com.dudu.utils.JSONUtils;
import com.dudu.utils.RequestUtils;
import com.dudu.utils.RequestUtils.ParamterParser;

import core.CoreDaoInvoke;
import core.CoreService;

/**
 * h5插件的post提交入口
 * 
 * @author zx
 *
 */
public class H5PostBootstrapController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String POST_ROUTER = "main1.html";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public H5PostBootstrapController() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding(RequestUtils.DEFAULT_CHARSET);
		String callerInfo = request.getParameter("caller");
		String companyInfo = request.getParameter("authData");
		String calleeInfo = request.getParameter("called");
		final JSONObject caller = JSONUtils.getJSON(callerInfo);
		if (caller == null) {// 主叫信息为空或格式错误
			doResponse(request, response, null, null, H5CodeDefinition.NULLORERROR_CALLERINFO.getMessage());
			return;
		}
		final JSONObject company = JSONUtils.getJSON(companyInfo);
		if (company == null) {// 组织（个人）信息为空或格式错误
			doResponse(request, response, null, null, H5CodeDefinition.NULLORERROR_COMPANYINFO.getMessage());
			return;
		}
		JSONArray callee = JSONUtils.getJSONArrayOrEmpty(calleeInfo);
		if (callee == null) {//// 参与人信息格式错误
			doResponse(request, response, null, null, H5CodeDefinition.ERROR_CALLEES.getMessage());
			return;
		}
		JSONObject rs = bootstrap(request, response);
		CoreService.log.info("h5启动服务返回结果:" + rs );
		/**
		 * 调用返回以下3种的，可以正常进入h5页面
		 * 1）返回成功-0000
		 * 2）账户余额不足-0017
		 * 3）账户未注册-0015
		 */
		if (!H5CodeDefinition.SUCCESS.getCode().equals(rs.getString("code"))
				&& !H5CodeDefinition.ACCOUNTBALANCE_INSUFFICIENT.getCode().equals(rs.getString("code"))
				&& !H5CodeDefinition.UNREGISTERED_COMPANYACCOUNT.getCode().equals(rs.getString("code"))) {// 调用启动服务错误
			doResponse(request, response, null, null,
					URLEncoder.encode(rs.getString("describe"), RequestUtils.DEFAULT_CHARSET));
			return;
		}
		String queryString = "?" + getQueryString(rs);
		queryString += RequestUtils.getParametersInQueryString(request, new ParamterParser() {
			public String parse(String parameterName, String parameterValue) {
				String value = parameterValue;
				if ("caller".equals(parameterName)) {
					String name = caller.getString("name");
					caller.put("name", RequestUtils.getEncodeParameter(name));
					value = caller.toString();
				} else if ("authData".equals(parameterName)) {
					String name = company.getString("ext_orgName");
					String linker = company.getString("ext_orgLinker");
					company.put("ext_orgName", RequestUtils.getEncodeParameter(name));
					company.put("ext_orgLinker", RequestUtils.getEncodeParameter(linker));
					value = company.toString();
				} else if ("called".equals(parameterName)) {
					/**
					 * 此处将被叫人设置为空，是为了避免url长度的限制带来的数据丢失问题
					 * 因为被叫人数可能会较多，后面采取返回html串的方式，由客户端缓存被叫人信息
					 */
					value = "";
				}
				return value;
			}
		});
		CoreService.log.info("path===" + POST_ROUTER + queryString);
		doResponse(request, response, POST_ROUTER + queryString, calleeInfo, null);
	}

	/**
	 * 调用h5插件的启动方法
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	private JSONObject bootstrap(HttpServletRequest request, HttpServletResponse response) {
		IH5Controller bootService = new H5Controller();
		CoreService service = (CoreService) bootService;
		service.setRequest(request);
		service.setResponse(response);
		service.setSession(request.getSession());
		service.setDao(CoreDaoInvoke.getInstance());
		String responseResult = bootService.bootstrap();
		return JSONObject.fromObject(responseResult).getJSONObject("data");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private void doResponse(HttpServletRequest request, HttpServletResponse response, String redirectUrl,
			String calleeInfo, String errorMessage) {
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try {
			out = response.getWriter();
			StringBuilder html = new StringBuilder(1200);
			html.append("<!doctype html><html><head><meta charset=\"UTF-8\"><title>启动页面</title>");
			html.append("<meta name='viewport' content='width=320,maximum-scale=1.3,user-scalable=no'>");
			html.append("<meta http-equiv=\"Cache-Control\" content=\"no-siteapp\" />");
			html.append("<meta name=\"screen-orientation\" content=\"portrait\">");
			html.append("<meta name=\"x5-orientation\" content=\"portrait\">");
			html.append("<meta content=\"email=no\" name=\"format-detection\">");
			html.append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\" />");
			html.append("<link rel=\"stylesheet\" href=\"css/yy_h5.css\">");
			html.append("<script type=\"text/javascript\" src=\"js/jquery.js\"></script>");
			html.append("<script type=\"text/javascript\" src=\"js/config.js\"></script>");
			html.append("<script type=\"text/javascript\" src=\"js/utils.js\"></script>");
			if (StringUtils.isEmpty(errorMessage)) {
				html.append("<script>$(function(){localCache.setSessionItems({contacts:'" + calleeInfo
						+ "'});location.assign('" + redirectUrl + "')})</script>");
			} else {
				html.append("<script>$(function(){new UserPrompt(decodeURI('").append(errorMessage)
						.append("'));})</script>"); 
			}
			html.append("</head><body></body></html>");
			out.print(html.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 解析json对象，返回querystring格式的字符串
	 * 例如：a=2&b=3
	 * @param object
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	private static String getQueryString(JSONObject object){
		if (object == null||object.isEmpty())
			return "";
		Iterator<String> ie = object.keys();
		StringBuilder values = new StringBuilder(128);
		while (ie.hasNext()) {
			String keyName = ie.next();
			String value=object.getString(keyName);
			if("describe".equals(keyName)){
				try {
					value=URLEncoder.encode(object.getString(keyName),RequestUtils.DEFAULT_CHARSET);
				} catch (UnsupportedEncodingException e) {
				}
			}
			values.append(keyName).append("=").append(value).append(RequestUtils.AMPERSAND_CHAR);
		}
		return values.toString();
	}

}
